package cn.edu.lingnan.controllerV1;

import cn.edu.lingnan.service.EmailService;
import cn.edu.lingnan.service.LoginService;
import cn.edu.lingnan.service.UserService;
import cn.edu.lingnan.user.dtos.ForgetPwdDto;
import cn.edu.lingnan.user.dtos.RegisterDto;
import cn.edu.lingnan.user.dtos.Result;
import cn.edu.lingnan.utils.RegexUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@RequestMapping("/have-email")
public class RegisterController {
    @Autowired
    private LoginService loginService;

   @Autowired
   private UserService userService;

    @Autowired
    private EmailService emailService;

    /**
     * 发送注册邮箱验证码
     * @param email
     * @return
     */
    @PostMapping("/send-register-code")
    public Result sendRegisterCode(@RequestParam String email) {

        return  emailService.sendRegisterCode(email);

    }

    //注册
    @PostMapping("/register")
    public Result register(@Valid @RequestBody RegisterDto registerDto, HttpServletRequest request) {
        return loginService.register(registerDto,request);
    }


    /**
     * 发送邮箱验证码
     */
    @PostMapping("/send-code")
    public Result sendCode(@RequestParam String to) {
        if (to == null || to.isEmpty()) {
            return Result.error("邮箱不能为空");
        }
        boolean validEmail = RegexUtils.isValidEmail(to);
        if (!validEmail) {
            return Result.error("邮箱格式不正确");
        }
        try {
            emailService.sendCode(to);
            return Result.success("验证码发送中，请稍后查看邮箱");
        } catch (Exception e) {
            log.error("发送验证码失败：{}", e.getMessage());
            return Result.error("验证码发送失败");
        }
    }

    /**
     * 邮箱验证登录
     *
     */
    @PostMapping("/login-email")
    public Result loginEmail(@RequestParam String email, @RequestParam String code, HttpServletRequest request) {
        return emailService.loginEmail(email, code, request.getSession());
    }

    //发送忘记密码-邮箱验证码
    @PostMapping("/sendResetPasswordCode")
    public Result sendResetPasswordCode(@RequestParam String email) {

        return emailService.sendResetPasswordCode(email);
    }

    //忘记密码
    @PostMapping("/resetPassword")
    public Result forgetPassword(@RequestBody ForgetPwdDto forgetPwdDto) {

        return  userService.forgetPassword(forgetPwdDto);
    }


}
